import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/foundation.dart'; // 用于kDebugMode

class PTZControlPanel extends StatefulWidget {
  final void Function(String command, {int? speed}) onControl;

  // 可选的PTZ控制可用性配置
  final bool canPanTilt;
  final bool canZoom;
  final bool canFocus;

  const PTZControlPanel({
    super.key,
    required this.onControl,
    this.canPanTilt = true,
    this.canZoom = true,
    this.canFocus = true,
  });

  @override
  State<PTZControlPanel> createState() => _PTZControlPanelState();
}

class _PTZControlPanelState extends State<PTZControlPanel> {
  int _controlSpeed = 5; // 1-10的速度范围
  Timer? _continuousControlTimer;
  String? _currentCommand;
  // 摇杆拖动状态已通过_joystickPosition判断，不需要额外标志
  Offset _joystickPosition = Offset.zero;
  final double _joystickRadius = 80.0;

  @override
  void dispose() {
    _continuousControlTimer?.cancel();
    super.dispose();
  }

  // 开始连续控制
  void _startContinuousControl(String command) {
    _currentCommand = command;
    _continuousControlTimer?.cancel();

    // 立即发送一次控制命令
    _sendControlCommand(command);

    // 设置定时器进行连续控制
    _continuousControlTimer =
        Timer.periodic(const Duration(milliseconds: 100), (timer) {
      _sendControlCommand(command);
    });
  }

  // 停止连续控制
  void _stopContinuousControl() {
    _continuousControlTimer?.cancel();
    _currentCommand = null;

    // 发送停止命令
    _sendControlCommand('stop');
  }

  // 发送控制命令
  void _sendControlCommand(String command) {
    try {
      widget.onControl(command, speed: _controlSpeed);
    } catch (e) {
      // 使用正确的错误处理方法，假设ErrorHandler有handlePtzError或类似方法
      // 如果没有专门的PTZ错误处理方法，可以使用其他通用方法或自定义错误对象
      if (kDebugMode) {
        print('PTZ control error: $e');
      }
      _continuousControlTimer?.cancel();
    }
  }

  // 处理摇杆拖动
  void _handleJoystickDragUpdate(DragUpdateDetails details) {
    if (!widget.canPanTilt) return;

    setState(() {
      // 限制摇杆在圆形区域内
      final delta =
          details.localPosition - Offset(_joystickRadius, _joystickRadius);
      final distance = delta.distance;

      if (distance <= _joystickRadius) {
        _joystickPosition = delta;
      } else {
        _joystickPosition = delta * (_joystickRadius / distance);
      }

      // 根据摇杆位置确定移动方向和速度
      _calculateMovement();
    });
  }

  // 处理摇杆结束拖动
  void _handleJoystickDragEnd() {
    setState(() {
      _joystickPosition = Offset.zero;
    });
    _stopContinuousControl();
  }

  // 根据摇杆位置计算移动方向和速度
  void _calculateMovement() {
    final x = _joystickPosition.dx;
    final y = _joystickPosition.dy;
    final distance = _joystickPosition.distance;

    // 计算速度比例 (0-1)
    final speedRatio = distance / _joystickRadius;
    final scaledSpeed = (speedRatio * 10).round();

    // 确定移动方向
    String direction = 'stop';

    if (distance > 10) {
      // 死区阈值
      if (x.abs() > y.abs()) {
        // 水平移动
        direction = x > 0 ? 'right' : 'left';
      } else {
        // 垂直移动
        direction = y > 0 ? 'down' : 'up';
      }
    }

    // 如果方向改变，停止之前的定时器并开始新的
    if (direction != _currentCommand && direction != 'stop') {
      _startContinuousControlWithSpeed(direction, scaledSpeed);
    } else if (direction == 'stop' && _currentCommand != null) {
      _stopContinuousControl();
    }
  }

  // 带速度参数的连续控制
  void _startContinuousControlWithSpeed(String command, int speed) {
    _currentCommand = command;
    _continuousControlTimer?.cancel();

    // 立即发送一次控制命令
    widget.onControl(command, speed: speed);

    // 设置定时器进行连续控制
    _continuousControlTimer =
        Timer.periodic(const Duration(milliseconds: 100), (timer) {
      widget.onControl(command, speed: speed);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(20),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          // 速度调节滑块
          if (widget.canPanTilt)
            Padding(
              padding: const EdgeInsets.only(bottom: 20),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const Text('速度调节:', style: TextStyle(color: Colors.white)),
                  Slider(
                    value: _controlSpeed.toDouble(),
                    min: 1,
                    max: 10,
                    divisions: 9,
                    onChanged: (value) {
                      setState(() {
                        _controlSpeed = value.round();
                      });
                    },
                    activeColor: Colors.blue,
                    inactiveColor: Colors.grey,
                    thumbColor: Colors.white,
                  ),
                  Text('$_controlSpeed',
                      style: const TextStyle(color: Colors.white)),
                ],
              ),
            ),

          // 主控制区 - 使用摇杆方式
          if (widget.canPanTilt)
            Stack(
              alignment: Alignment.center,
              children: [
                // 摇杆背景圆
                Container(
                  width: _joystickRadius * 2,
                  height: _joystickRadius * 2,
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    border: Border.all(color: Colors.white, width: 2),
                    color: Colors.black.withOpacity(0.5),
                  ),
                ),

                // 方向指示器（可选）
                Column(
                  children: [
                    Icon(Icons.arrow_upward,
                        color: Colors.white.withOpacity(0.5), size: 20),
                    Row(
                      children: [
                        Icon(Icons.arrow_back,
                            color: Colors.white.withOpacity(0.5), size: 20),
                        const SizedBox(width: 50),
                        Icon(Icons.arrow_forward,
                            color: Colors.white.withOpacity(0.5), size: 20),
                      ],
                    ),
                    Icon(Icons.arrow_downward,
                        color: Colors.white.withOpacity(0.5), size: 20),
                  ],
                ),

                // 摇杆（可拖动部分）
                Positioned(
                  left: _joystickRadius - 20 + _joystickPosition.dx,
                  top: _joystickRadius - 20 + _joystickPosition.dy,
                  child: GestureDetector(
                    onPanUpdate: _handleJoystickDragUpdate,
                    onPanEnd: (details) => _handleJoystickDragEnd(),
                    onPanCancel: _handleJoystickDragEnd,
                    child: Container(
                      width: 40,
                      height: 40,
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        color: Colors.blue,
                        boxShadow: [
                          BoxShadow(
                            color: Colors.white.withOpacity(0.5),
                            spreadRadius: 1,
                            blurRadius: 3,
                          ),
                        ],
                      ),
                      child: const Icon(Icons.pan_tool,
                          color: Colors.white, size: 20),
                    ),
                  ),
                ),
              ],
            ),

          const SizedBox(height: 30),

          // 缩放和聚焦控制
          if (widget.canZoom || widget.canFocus)
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                // 缩放控制
                if (widget.canZoom)
                  Column(
                    children: [
                      const Text('缩放',
                          style: TextStyle(color: Colors.white, fontSize: 12)),
                      const SizedBox(height: 5),
                      GestureDetector(
                        onTap: () => _sendControlCommand('zoom_in'),
                        onLongPressStart: (_) =>
                            _startContinuousControl('zoom_in'),
                        onLongPressUp: () => _stopContinuousControl(),
                        child: Container(
                          padding: const EdgeInsets.all(8),
                          child: const Icon(Icons.zoom_in,
                              color: Colors.white, size: 28),
                        ),
                      ),
                      GestureDetector(
                        onTap: () => _sendControlCommand('zoom_out'),
                        onLongPressStart: (_) =>
                            _startContinuousControl('zoom_out'),
                        onLongPressUp: () => _stopContinuousControl(),
                        child: Container(
                          padding: const EdgeInsets.all(8),
                          child: const Icon(Icons.zoom_out,
                              color: Colors.white, size: 28),
                        ),
                      ),
                    ],
                  ),

                const SizedBox(width: 60),

                // 聚焦控制
                if (widget.canFocus)
                  Column(
                    children: [
                      const Text('聚焦',
                          style: TextStyle(color: Colors.white, fontSize: 12)),
                      const SizedBox(height: 5),
                      GestureDetector(
                        onTap: () => _sendControlCommand('focus_in'),
                        onLongPressStart: (_) =>
                            _startContinuousControl('focus_in'),
                        onLongPressUp: () => _stopContinuousControl(),
                        child: Container(
                          padding: const EdgeInsets.all(8),
                          child: const Icon(Icons.add,
                              color: Colors.white, size: 28),
                        ),
                      ),
                      GestureDetector(
                        onTap: () => _sendControlCommand('focus_out'),
                        onLongPressStart: (_) =>
                            _startContinuousControl('focus_out'),
                        onLongPressUp: () => _stopContinuousControl(),
                        child: Container(
                          padding: const EdgeInsets.all(8),
                          child: const Icon(Icons.remove,
                              color: Colors.white, size: 28),
                        ),
                      ),
                    ],
                  ),
              ],
            ),

          const SizedBox(height: 20),

          // 预设位置和重置按钮
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ElevatedButton(
                onPressed: () => _sendControlCommand('reset'),
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.grey.shade700,
                  foregroundColor: Colors.white,
                ),
                child: const Text('重置'),
              ),
              const SizedBox(width: 20),
              ElevatedButton(
                onPressed: () => _sendControlCommand('preset_home'),
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.blue.shade700,
                  foregroundColor: Colors.white,
                ),
                child: const Text('回到预设位'),
              ),
            ],
          ),
        ],
      ),
    );
  }
}
